package com.boot.study.udf

import com.boot.study.api.SensorReading
import org.apache.flink.streaming.api.TimeCharacteristic
import org.apache.flink.streaming.api.functions.timestamps.BoundedOutOfOrdernessTimestampExtractor
import org.apache.flink.streaming.api.scala._
import org.apache.flink.streaming.api.windowing.time.Time
import org.apache.flink.table.api._
import org.apache.flink.table.api.scala._
import org.apache.flink.table.functions.TableFunction
import org.apache.flink.types.Row

object TableFunctionTest {
  def main(args: Array[String]): Unit = {
    // 1: 创建环境
    val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment
    env.setParallelism(1)
    // TimeCharacteristic.EventTime 事件时间
    // TimeCharacteristic.ProcessingTime 处理时间
    env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime) // 时间语义，处理时间

    // 创建表执行环境
    val settings: EnvironmentSettings = EnvironmentSettings.newInstance()
      .useBlinkPlanner()
      .inStreamingMode()
      .build()
    val tableEnv: StreamTableEnvironment = StreamTableEnvironment.create(env, settings)

    val inputPath: String = "D:\\WorkSpace\\idea\\Flink\\src\\main\\resources\\sensor.txt"
    val inputSteam: DataStream[String] = env.readTextFile(inputPath)
    val dataStream: DataStream[SensorReading] = inputSteam.map(data => {
      val arr: Array[String] = data.split(",")
      SensorReading(arr(0), arr(1).toLong, arr(2).toDouble)
    })
      // 延迟1秒生成 watermark
      .assignTimestampsAndWatermarks(new BoundedOutOfOrdernessTimestampExtractor[SensorReading](Time.seconds(1)) {
        override def extractTimestamp(element: SensorReading): Long = element.timeStamp * 1000
      })
    val sensorTable: Table = tableEnv.fromDataStream(dataStream, 'id, 'temperature, 'timeStamp.rowtime as 'ts)
    // 1: table api
    val spilt = new Spilt("_") // new 一个udf
    val resultTable: Table = sensorTable
      .joinLateral(spilt('id) as('word, 'length)) // 侧向连接
      .select('id, 'ts, 'word, 'length)

    // 2:sql实现
    tableEnv.createTemporaryView("sensor", sensorTable)
    tableEnv.registerFunction("spilt", spilt)
    val resultSqlTable: Table = tableEnv.sqlQuery(
      """
        | select
        |  id,ts,word,length
        | from
        | sensor,lateral table( spilt(id) ) as spiltid(word,length)
        |""".stripMargin)

    // 3: 输出
    resultTable.toAppendStream[Row].print("table")
    resultSqlTable.toAppendStream[Row].print("sql")

    env.execute("table function test")
  }
}

// 自定义TableFunction
class Spilt(separator: String) extends TableFunction[(String, Int)] {
  def eval(str: String) = {
    str.split(separator).foreach(word => collect((word, word.length)))
  }
}